# 谢尔宾斯基三角形
import math
import random
import turtle


# 画三角形
def draw_triangle(pos):
    turtle.penup()
    turtle.goto(pos[0])
    turtle.pendown()
    for i in [1, 2, 0]:
        turtle.goto(pos[i])


# 获取一个随机点
def getRandomPos(x, y):
    return random.randint(-x / 2, x / 2), random.randint(-y / 2, y / 2)


# 获取两点中间坐标
def getMidPos(p1, p2):
    return (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2


# 入参为三角形三个点的初始坐标
def sierpinski(*pos):
    # 画三角形
    draw_triangle(pos)
    p1, p2, p3 = pos
    # 在三角形内随机取一个点
    randX = (p1[0] + p2[0]) / random.randint(2,10)
    randY = (p2[1] + p3[1]) / random.randint(2,10)
    for i in range(10000):
        # 画点
        turtle.penup()
        turtle.goto(randX, randY)
        turtle.pendown()
        turtle.dot(3)
        # 随机选择一个顶点
        rand_i = random.randint(0, 2)
        randVer = pos[rand_i]
        # 计算该点到顶点的中心点
        randX = (randX + randVer[0]) / 2
        randY = (randY + randVer[1]) / 2


def main():
    turtle.title("谢尔宾斯基三角形")
    width = 900
    height = 600
    startX = 200
    startY = 100
    turtle.setup(width, height, startX, startY)
    turtle.pensize(2)
    turtle.tracer(2)
    turtle.hideturtle()
    turtle.bgcolor("#000")
    turtle.pencolor("#fff")
    # 任取三个点
    p1 = getRandomPos(width - 20, height - 20)
    p2 = getRandomPos(width - 20, height - 20)
    p3 = getRandomPos(width - 20, height - 20)
    sierpinski(p1, p2, p3)
    turtle.done()


main()
